package com.csun.nusing.ui.familyactivity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.csun.nusing.R;
import com.csun.nusing.bean.UrlBean;
import com.csun.nusing.bean.jsonbean.PhoneJsonBean;
import com.csun.nusing.presenter.CommonPresenter;
import com.csun.nusing.ui.BaseActivity;
import com.csun.nusing.ui.activity.HelpCenterActivity;
import com.csun.nusing.ui.activity.UserBookActivity;
import com.csun.nusing.ui.activity.VersionNumberActivity;
import com.csun.nusing.util.DialogUtils;
import com.csun.nusing.util.GlideCacheUtil;
import com.csun.nusing.util.SPUtils;
import com.google.gson.Gson;
import com.home.administrator.okhttplibrary.IOkTaskCallback;
import com.home.administrator.okhttplibrary.OkHttpTask;

import java.util.HashMap;
import java.util.Map;

/**
 * 设置界面 ClassName: NursingSettingActivity
 *
 * @author fzq
 * @Description: TODO
 * @date 2017-11-2
 */
public class FamilySettingActivity extends BaseActivity<CommonPresenter> {

    private TextView clearcachetv;
    private TextView cachetv;
    private GlideCacheUtil glidecache;
    private String cachesize;
    private TextView versiontv;//版本查看接口
    private Switch settingswitch;
    private TextView helptv;
    private TextView serverphonetv;
    private TextView userbooktv;

    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;
    private String phonenumber = "4008351112";
    private String authorization;

    @Override
    public int getContentViewId() {
        return R.layout.activity_family_setting;
    }

    @Override
    public void initSubViews(View view) {
        super.initSubViews(view);
        initView();
    }

    private void initView() {
        clearcachetv = findViewById(R.id.family_setting_clearcache_tv);
        versiontv = findViewById(R.id.family_setting_versioncode_tv);
        cachetv = findViewById(R.id.family_setting_cache_tv);
        helptv = findViewById(R.id.family_setting_help_tv);
        serverphonetv = findViewById(R.id.family_setting_server_phone_tv);
        userbooktv = findViewById(R.id.family_setting_user_book_tv);
        settingswitch = findViewById(R.id.family_setting_switch);
        settingswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    SPUtils.put(FamilySettingActivity.this, "upLogFlag", true);
                } else {
                    SPUtils.put(FamilySettingActivity.this, "upLogFlag", false);
                }
            }
        });
        clearcachetv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getConfirmDialog(FamilySettingActivity.this, getString(R.string.is_delete_cache),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(
                                    DialogInterface dialogInterface, int i) {
                                clearcache();
                            }
                        }).show();
            }
        });
        serverphonetv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                phone();
            }
        });
        userbooktv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(FamilySettingActivity.this, UserBookActivity.class);
                intent.putExtra("isFamily", true);
                startActivity(intent);
            }
        });
        helptv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(FamilySettingActivity.this, HelpCenterActivity.class);
                intent.putExtra("isFamily", true);
                startActivity(intent);
            }
        });
        versiontv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(FamilySettingActivity.this, VersionNumberActivity.class);
                intent.putExtra("isFamily", true);
                startActivity(intent);
            }
        });

    }

    /**
     * 拨打客服电话功能
     */
    private void phone() {
        DialogUtils.showTitleMessageDialog(this, getString(R.string.take_phone), getString(R.string.ke_fu_time), new DialogUtils.OnButtonClickListener() {
            @Override
            public void onConfirmButtonClick() {
                // 检查是否获得了权限（Android6.0运行时权限）
                if (ContextCompat.checkSelfPermission(FamilySettingActivity.this,
                        Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // 没有获得授权，申请授权
                    if (ActivityCompat.shouldShowRequestPermissionRationale(FamilySettingActivity.this,
                            Manifest.permission.CALL_PHONE)) {
                        // 返回值：
//                          如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
//                          如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
//                          如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                        // 弹窗需要解释为何需要该权限，再次请求授权
                        Toast.makeText(FamilySettingActivity.this, "请授权！", Toast.LENGTH_SHORT).show();

                        // 帮跳转到该应用的设置界面，让用户手动授权
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        startActivity(intent);
                    } else {
                        // 不需要解释为何需要该权限，直接请求授权
                        ActivityCompat.requestPermissions(FamilySettingActivity.this,
                                new String[]{Manifest.permission.CALL_PHONE},
                                MY_PERMISSIONS_REQUEST_CALL_PHONE);
                    }
                } else {
                    // 已经获得授权，可以打电话
                    CallPhone();
                }
            }

            @Override
            public void onCancelButtonClick() {
                super.onCancelButtonClick();
            }
        });
    }


    /**
     * 拨号
     */
    private void CallPhone() {
        // 拨号：激活系统的拨号组件
        Intent intent = new Intent(); // 意图对象：动作 + 数据
        intent.setAction(Intent.ACTION_CALL); // 设置动作
        Uri data = Uri.parse("tel:" + phonenumber); // 设置数据
        intent.setData(data);
        startActivity(intent); // 激活Activity组件
    }

    // 处理权限申请的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL_PHONE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 授权成功，继续打电话
                    CallPhone();
                } else {
                    // 授权失败！
                    Toast.makeText(this, "授权失败！", Toast.LENGTH_LONG).show();
                }
                break;
            }
        }

    }


    /**
     * 清除glide缓存
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-11-7
     */
    private void clearcache() {
        // 获取缓存大小
        // 清除缓存
        glidecache.clearImageAllCache(this);
        glidecache.clearImageDiskCache(this);
        glidecache.clearImageMemoryCache(this);
        cachetv.setText("0KB");
    }


    /**
     * dialog
     *
     * @param @param  context
     * @param @param  message
     * @param @param  onClickListener
     * @param @return
     * @return AlertDialog.Builder
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-11-2
     */
    public static AlertDialog.Builder getConfirmDialog(Context context,
                                                       String message, DialogInterface.OnClickListener onClickListener) {
        AlertDialog.Builder builder = getDialog(context);
        builder.setMessage(Html.fromHtml(message));
        builder.setPositiveButton(R.string.enter, onClickListener);
        builder.setNegativeButton(R.string.cancel, null);
        return builder;
    }

    public static AlertDialog.Builder getDialog(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        return builder;
    }

    @Override
    public void initData() {
        super.initData();
        glidecache = GlideCacheUtil.getInstance();
        cachesize = glidecache.getCacheSize(this);
        cachetv.setText("" + cachesize);
        Map<String, String> param = new HashMap<String, String>();
//        PHONESHOWURL
        authorization = (String) SPUtils
                .get(this, "authorization", "");
        OkHttpTask.newInstance(this).post(param, OkHttpTask.OkHttpTaskBuidler.OkType.form)
                .addHeader("authorization", authorization)
                .enqueue(new IOkTaskCallback() {
                    @Override
                    public void onSuccess(String result) {
                        if (result != null) {
                            Log.e("fzq","result  "+result);
                            Gson gson = new Gson();
                            PhoneJsonBean phonebean = gson.fromJson(result, PhoneJsonBean.class);
                            if (phonebean.isStatus()) {
                                if (phonebean.getData() != null && phonebean.getData().size() != 0) {
                                    if (phonebean.getData().get(0).getPhone() != null) {
                                        phonenumber = phonebean.getData().get(0).getPhone();
                                        serverphonetv.setText(phonenumber);
                                    }
                                }
                            }

                        }
                    }
                }).start(UrlBean.PHONESHOWURL);


    }

}
